<template>
  <div class="dv-scroll-board" ref="scrollBoardRef">
    <!-- 表头区域 -->
    <div class="table-header" v-if="config.headerHide">
      <div class="header-cell" v-for="(headerItem, i) in header" :key="`${headerItem}${i}`" 
       :align="aligns[i]" v-html="headerItem" />
    </div>

    <!-- 滚动内容区域 -->
    <div v-if="config" class="scroll-content-wrapper"
      :style="`height: ${height - (header.length ? config.headerHeight : 0)}px;`" @mouseenter="pauseScroll"
      @mouseleave="resumeScroll">
      <div class="scroll-content" :style="{ transform: `translateY(${scrollPosition}px)` }">
        <!-- 数据行 -->
        <div v-for="(item, index) in displayItems" :key="index" class="table-row" :class="{
          'warning': item.rawData.status === 'warring',
          'success': item.rawData.status === 'success'
        }">
          <div class="table-cell" v-for="(ceil, ci) in item.ceils" :key="`${ceil}${index}${ci}`"
            :align="aligns[ci]"
            @click="emitEvent('click', index, ci, item, ceil)" @mouseenter="handleHover(true, index, ci, item, ceil)"
            @mouseleave="handleHover(false)" >
            <div v-if="ci!=4" v-html="ceil"></div>
            <div class="status" v-else>
               <Precent  v-if="item.rawData.status === 'on'" :plan="item.rawData.progress" ></Precent>
                <span v-else></span>{{ item.rawData.status === 'warring' ? '延期' : `${item.rawData.progress}%`}}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import Precent from './precent.vue'
import { ref, computed, onMounted, onUnmounted, watch, nextTick, toRefs } from 'vue';

// 组件 props
const props = defineProps({
  config: {
    type: Object,
    default: () => ({})
  }
});

// 组件状态
const scrollBoardRef = ref(null);
const scrollPosition = ref(0);
const currentIndex = ref(0);
const rowHeight = ref(0);
const timer = ref(null);
const isPaused = ref(false);
const width = ref(0);
const height = ref(0);

// 默认配置
const defaultConfig = {
  header: [],
  data: [],
  rowNum: 4,
  headerBGC: '#00BAFF',
  oddRowBGC: '#003B51',
  evenRowBGC: '#0A2732',
  waitTime: 2000,
  headerHeight: 33,
  headerHide:false,
  columnWidth: [],
  align: [],
  index: false,
  indexHeader: '#',
  carousel: 'single',
  hoverPause: true
};

// 手动实现深拷贝
const deepClone = (obj) => {
  if (obj === null || typeof obj !== 'object') {
    return obj;
  }

  if (Array.isArray(obj)) {
    return obj.map(item => deepClone(item));
  }

  const clone = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      clone[key] = deepClone(obj[key]);
    }
  }
  return clone;
};

// 手动实现深度合并
const deepMerge = (target, source) => {
  if (typeof target !== 'object' || target === null) {
    return deepClone(source);
  }

  if (typeof source !== 'object' || source === null) {
    return deepClone(target);
  }

  Object.keys(source).forEach(key => {
    if (source.hasOwnProperty(key)) {
      if (Array.isArray(target[key]) && Array.isArray(source[key])) {
        target[key] = target[key].concat(source[key].map(item => deepClone(item)));
      } else if (typeof target[key] === 'object' && typeof source[key] === 'object') {
        target[key] = deepMerge(target[key], source[key]);
      } else {
        target[key] = deepClone(source[key]);
      }
    }
  });

  return target;
};

// 计算属性
const config = computed(() => {
  const merged = { ...defaultConfig };

  // 手动深度合并配置
  for (const key in props.config) {
    if (props.config.hasOwnProperty(key)) {
      if (typeof props.config[key] === 'object' &&
        props.config[key] !== null &&
        !Array.isArray(props.config[key])) {
        merged[key] = { ...merged[key], ...props.config[key] };
      } else {
        merged[key] = props.config[key];
      }
    }
  }

  return merged;
});

const header = computed(() => {
  const { header, index, indexHeader } = config.value;
  if (!header || !header.length) return [];
  let titles = header.map(item => item.title);
  if (index) {
    titles.unshift(indexHeader);
  }
  return titles;
});

const rowsData = computed(() => {
  const { data, index, headerBGC, rowNum, header } = config.value;
  if (!data || !data.length || !header || !header.length) return [];

  // 从表头配置中提取显示字段和顺序，过滤掉隐藏的列
  const fields = header
    .filter(col => col.isHide !== 'true') // 排除 isHide 为 true 的列
    .map(col => ({
      key: col.key || Object.keys(data[0])[header.indexOf(col)], // 使用配置的key或默认位置
      title: col.title
    }));

  let newData = data.map((row, i) => {
    // 从对象中提取字段值并转换为数组
    const rowData = fields.map(field => {
      const value = row[field.key] || '';
      
      // 特殊处理status字段，可以根据需要调整
      if (field.key === 'status') {
        return value === 'on' ? '进行中' : '已完成';
      }
      
      // 特殊处理progress字段，添加进度条显示
      if (field.key === 'progress') {
        return `<div class="progress-bar" style="width: ${value}%;">${value}%</div>`;
      }
      
      return value;
    });

    if (index) {
      const indexTag = `<span class="index" style="background-color: ${headerBGC};">${i + 1}</span>`;
      rowData.unshift(indexTag);
    }
    
    return { ceils: rowData, rowIndex: i,rawData: row };
  });

  // 为实现无缝滚动，在数据首尾添加重复项
  const dataLength = newData.length;
  if (dataLength > rowNum && dataLength < 2 * rowNum) {
    newData = [...newData, ...newData];
  }

  return newData.map((d, i) => ({ ...d, scrollIndex: i }));
});

const displayItems = computed(() => {
 if (!rowsData.value.length || rowsData.value.length <= config.value.rowNum) {
    return rowsData.value; // 数据量少，直接显示
  }

  const visibleRows = config.value.rowNum;
  // 只保留尾部重复项（用于滚动到末尾时衔接），去掉头部重复项
  const tail = rowsData.value.slice(0, visibleRows); 
  console.log(2222222222,[...rowsData.value, ...tail])
  return [...rowsData.value, ...tail]; // 组合：原始 + 开头N条
});

const widths = computed(() => {
  const { columnWidth, header } = config.value;
  const columnNum = header.length;
  const usedWidth = (columnWidth || []).reduce((all, w) => all + w, 0);
  const avgWidth = (width.value - usedWidth) / (columnNum - (columnWidth || []).length);
  const widths = new Array(columnNum).fill(avgWidth);

  // 手动合并列宽配置
  if (columnWidth && columnWidth.length) {
    columnWidth.forEach((w, i) => {
      if (i < widths.length) {
        widths[i] = w;
      }
    });
  }

  return widths;
});

const aligns = computed(() => {
  const columnNum = header.value.length;
  let aligns = new Array(columnNum).fill('left');
  const { align } = config.value;

  // 手动合并对齐配置
  if (align && align.length) {
    align.forEach((a, i) => {
      if (i < aligns.length) {
        aligns[i] = a;
      }
    });
  }

  return aligns;
});

// 生命周期钩子
onMounted(() => {
  initComponent();
  startScroll();

  // 监听窗口大小变化
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  stopScroll();
  window.removeEventListener('resize', handleResize);
});

// 监听配置变化
watch(() => props.config, () => {
  initComponent();
  stopScroll();
  startScroll();
});

// 初始化组件
const initComponent = async () => {
  await nextTick();

  // 获取容器尺寸
  if (scrollBoardRef.value) {
    width.value = scrollBoardRef.value.clientWidth;
    height.value = scrollBoardRef.value.clientHeight;
  }

  // 计算行高
  const firstRow = document.querySelector('.table-row');
  if (firstRow) {
    rowHeight.value = firstRow.offsetHeight;
    // 初始位置：跳过开头的复制项
    scrollPosition.value = 0;
  }
};

// 处理窗口大小变化
const handleResize = () => {
  if (!scrollBoardRef.value) return;

  width.value = scrollBoardRef.value.clientWidth;
  height.value = scrollBoardRef.value.clientHeight;
};

// 轮播控制
const startScroll = () => {
  if (timer.value || !rowsData.value.length || rowsData.value.length <= config.value.rowNum) {
    return;
  }

  timer.value = setInterval(() => {
    if (isPaused.value) return;

    currentIndex.value++;

    // 无缝滚动逻辑
    if (currentIndex.value >= rowsData.value.length) {
      currentIndex.value = 0;
      scrollPosition.value = -config.value.rowNum * rowHeight.value;
    } else {
      scrollPosition.value -= rowHeight.value;
    }
  }, config.value.waitTime);
};

const stopScroll = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
};

const pauseScroll = () => {
  if (config.value.hoverPause) {
    isPaused.value = true;
  }
};

const resumeScroll = () => {
  if (config.value.hoverPause) {
    isPaused.value = false;
  }
};

// 事件处理
const handleHover = (enter, ri, ci, row, ceil) => {
  if (enter) emitEvent('mouseover', ri, ci, row, ceil);
};

const emitEvent = (type, ri, ci, row, ceil) => {
  // const { ceils, rowIndex } = row;
  // const emit = defineEmits([type]);
  // emit(type, {
  //   row: ceils,
  //   ceil,
  //   rowIndex,
  //   columnIndex: ci
  // });
};

// 外部更新数据
const updateRows = (rows, animationIndex) => {
  props.config.data = [...rows];

  if (typeof animationIndex === 'number') {
    currentIndex.value = animationIndex;
  }

  // 重新计算数据
  initComponent();
  stopScroll();
  startScroll();
};
</script>

<style scoped lang="less">
.dv-scroll-board {
  position: relative;
  width: 100%;
  height: 100%;
  color: #fff;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .table-header {
    color: #02a6f6;
    background: rgba(9, 25, 53, 0.9);
    display: flex;

    .header-cell {
      width: 100px;
      font-size: 14px;
      padding: 12px 0 12px 10px;
      display: flex;
      align-items: center;
      justify-content: start;
    }
  }

  .scroll-content-wrapper {
    flex: 1;
    overflow: hidden;
    position: relative;
  }

  .scroll-content {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    transition: transform 0.5s ease-in-out;

    .table-row {
      display: flex;
      color: #d0deee;
    }
    .warning {
        background: rgba(241, 17, 17, 0.44);

        .table-cell {

          &:nth-child(3),
          &:nth-child(5) {
            color: #ff3b3b;
          }

          span {
            background: url(@/assets/img/warring.png) no-repeat center;
            background-size: contain;
          }
        }
        
      }

      .success {
        .table-cell {
          span {
            background: url(@/assets/img/success.png) no-repeat center;
            background-size: contain;
          }
        }
      }

    .table-row:last-child {
      border-bottom: none;
    }


    .table-cell {
      width: 100px;
      font-size: 14px;
      padding: 12px 0 12px 10px;
      display: flex;
      align-items: center;
      justify-content: start;
      .status{
          display: flex;
          align-items: center;
          justify-content: start;
        }

      span {
        display: block;
        width: 16px;
        height: 16px;
        margin-right: 5px;
      }
    }
  }

  .index {
    display: inline-block;
    width: 20px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border-radius: 4px;
    margin-right: 5px;
  }
}
</style>